package company

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jwgin/model/mysql"
	"jwgin/service"
)

type link struct {
}

func (l *link) Routers(Router *gin.RouterGroup) {
	//资源列表
	Router.GET("link", l.get)   //列表
	Router.POST("link", l.post) //更新
	Router.PUT("link", l.put)   //新加
}

func (l *link) get(c *gin.Context) {

	UserID := c.GetUint("UserID")
	if UserID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}

	count, size, offset := pages(c)
	db := service.G.Model(mysql.Link{}).Where("comid = ? ", UserID)
	if statu := c.Query("statu"); statu != "" {
		db = db.Where("link_statu = ?", statu)
	}
	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" addtime > ? AND addtime < ? ", startTime, endTime)
	}

	list := []map[string]interface{}{}
	db.Count(&count).Offset(offset).Limit(size).Order("id DESC").Scan(&list)
	RespList(c, count, list)
}
func (l *link) post(c *gin.Context) {
	q := &mysql.Link{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}

	if q.Id < 1 {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	err := service.G.Save(q).Error
	if err != nil {
		RespErr(c, err)
		return
	}
	RespSucc(c, nil)
}
func (l *link) put(c *gin.Context) {
	q := &mysql.Link{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}
	UserID := c.GetUint("UserID")
	if UserID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	q.Comid = int(UserID)
	if err := service.G.Create(q).Error; err != nil {
		RespErr(c, err)
	} else {
		RespSucc(c, nil)
	}
}
